package com.yanqu.road.server.gameplayer.module.activity.peakseacraft;

import com.yanqu.road.entity.activity.peakseacraft.PeakSeacraftCellInfo;
import com.yanqu.road.entity.activity.peakseacraft.PeakSeacraftUserData;
import com.yanqu.road.entity.activity.peakseacraft.config.PeakSeacraftActivityConfig;
import com.yanqu.road.entity.activity.peakseacraft.config.PeakSeacraftDonateConfig;
import com.yanqu.road.entity.activity.seacraft.config.SeacraftSouthSeaFloorConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.logic.bussiness.activity.PeakSeacraftBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.RandomWeightConfigHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.PeakSeacraftProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.peakseacraft.PeakSeacraftMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description  海上争霸 之 南海丝路
 */
public class PeakSeacraftModule extends GeneralModule {

    private PeakSeacraftUserData userData;

    public PeakSeacraftModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        if (PeakSeacraftMgr.getActivityInfo() != null && ActivityMgr.activityInShowTime(PeakSeacraftMgr.getActivityInfo())) {
            userData = PeakSeacraftBusiness.getPeakSeacraftUserData(PeakSeacraftMgr.getActivityInfo().getActivityId(), this.getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public void afterLogin() {
        initUserData();
        sendConfigToClient();
        synUserData();
    }

    @Override
    public boolean saveData() {
        if (null != userData) {
            if (userData.isInsertOption()) {
                PeakSeacraftBusiness.addPeakSeacraftUserData(userData);
            } else if (userData.isUpdateOption()) {
                PeakSeacraftBusiness.updatePeakSeacraftUserData(userData);
            }
        }
        return true;
    }

    public void initUserData() {
        if (PeakSeacraftMgr.getActivityInfo() == null || !ActivityMgr.activityInShowTime(PeakSeacraftMgr.getActivityInfo())) {
            return;
        }
        if(!SystemOpenMgr.systemOpen(player, eSystemId.PeakSeacraft.getValue())){
            return;
        }

        if (userData == null) {
            userData = new PeakSeacraftUserData();
            userData.setActivityId(PeakSeacraftMgr.getActivityInfo().getActivityId());
            userData.setUserId(this.getUserId());
            userData.setRound(PeakSeacraftMgr.getConfig().getCurRound());
            userData.setDonationExp(0);
            userData.setSilverDonateNum(0);
            userData.setCellInfoList(new ArrayList<>());
            userData.setFloor(0);
            userData.setGotBigReward(0);
            userData.setInsertOption();
        }
    }

    public void initSystem() {
        initUserData();
        sendConfigToClient();
        synUserData();
    }

    public void synUserData() {
        // 向跨服 获取玩家数据
        if (PeakSeacraftMgr.getActivityInfo() == null || !SystemOpenMgr.systemOpen(player, eSystemId.PeakSeacraft.getValue()) || PeakSeacraftMgr.getConfig() == null) {
            return;
        }
        initUserData();
        if (null == userData) {
            return;
        }
        roundReset();
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        PeakSeacraftProto.PeakSeacraftGetUserDataGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftGetUserDataGameToCrossMsg.newBuilder();
        gameToCrossMsg.setUnionId(ownUnionId);
        gameToCrossMsg.setActivityId(PeakSeacraftMgr.getActivityInfo().getActivityId());
        gameToCrossMsg.setFloor(userData.getFloor());
        gameToCrossMsg.setSilverDonateNum(userData.getSilverDonateNum());
        gameToCrossMsg.setWorship(userData.getWorship());
        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_GET_USER_DATA, gameToCrossMsg, gameToCrossMsg.getActivityId());
    }

    /**
     * 轮次重置
     */
    public synchronized void roundReset() {
        PeakSeacraftActivityConfig config = PeakSeacraftMgr.getConfig();
        if (null == config) {
            return;
        }
        if (null == userData) {
            return;
        }
        int curRound = config.getCurRound();
        if (userData.getRound() != config.getCurRound()) {
            userData.setRound(curRound);
            userData.setSilverDonateNum(0);

            String language = player.getLanguage();
            CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
            BagModule bagModule = player.getModule(BagModule.class);
            Property cost = new Property();
            Property reward = new Property();
            Map<String, Long> recycleNameNumMap = new HashMap<>();
            //回收船桨和火药
            for (Integer paddleItemId : config.getPaddleItemIdList()) {
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(paddleItemId);
                if (null == goodsInfo) {
                    continue;
                }
                long num = bagModule.getUserBagItemCount(paddleItemId);
                if (num > 0) {
                    cost.addProperty(paddleItemId, BigInteger.valueOf(num));
                    recycleNameNumMap.put(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), language), num);
                    for (int i = 0; i < num; i++) {
                        OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(paddleItemId);
                        if (null != openGoodsBagResult) {
                            reward.addProperty(openGoodsBagResult.getReward());
                        }
                    }
                }
            }

            int fireItemId = config.getSEACRAFT_CRAFT_FIRE_ITEM_ID();
            long fireItemNum = bagModule.getUserBagItemCount(fireItemId);
            if (fireItemNum > 0) {
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(fireItemId);
                if (null != goodsInfo) {
                    cost.addProperty(fireItemId, BigInteger.valueOf(fireItemNum));
                    recycleNameNumMap.put(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), language), fireItemNum);
                    for (int i = 0; i < fireItemNum; i++) {
                        OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(fireItemId);
                        if (null != openGoodsBagResult) {
                            reward.addProperty(openGoodsBagResult.getReward());
                        }
                    }
                }
            }

            if (!cost.isNothing()) {
                if (!currencyModule.removeCurrency(cost, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityRoundRecycleCost)) {
                    return;
                }
            }

            if (!reward.isNothing() && !recycleNameNumMap.isEmpty()) {
                StringBuilder returnStr = new StringBuilder();
                for (Map.Entry<String, Long> entry : recycleNameNumMap.entrySet()) {
                    String key = entry.getKey();
                    Long value = entry.getValue();
                    returnStr.append(ServerLanguageMgr.getContent(key, language)).append("X").append(value).append(", ");
                }
                String mailTitle = MultipleLanguageMgr.getContent(MailManager.PEAKSEACRAFT_REMOVE_ITEM_TITLE, language);
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.PEAKSEACRAFT_REMOVE_ITEM_CONTENT,
                        language), returnStr.toString());
                MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(reward), mailContent, mailTitle);
            }
        }
    }


    /**
     * 同步配置
     */
    public void sendConfigToClient() {
        if (PeakSeacraftMgr.getActivityInfo() == null || !SystemOpenMgr.systemOpen(player, eSystemId.PeakSeacraft.getValue()) || PeakSeacraftMgr.getConfig() == null) {
            return;
        }
        player.sendPacket(ClientProtocol.U_PEAK_SEACRAFT_CONFIG, PeakSeacraftMgr.builderPeakSeacraftConfig(player.getLanguage()));
    }

    /**
     * 同步玩家积分
     * @param allScore
     */
    public void synUserScore(int allScore){
        if(allScore > 0){
            player.notifyListener(eGamePlayerEventType.PeakSeacraftUserScoreRank.getValue(), allScore);
        }
    }

    /**
     * 战斗结束
     */
    public void battleEnd(PeakSeacraftProto.PeakSeacraftChallengeResult result){
        if(result != null){
            // 加勋章道具
            Property reward = new Property(PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_SCORE_ITEM_ID(), result.getGetMedalNum());
            reward.addProperty(PropertyHelper.parseStringToProperty(result.getBattleReward()));
            // 加战斗奖励
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityChallengeReward);
        }
    }

    /**
     * 捐献
     * type:1银两 2材料
     */
    public int donate(int type, int num) {
        PeakSeacraftActivityConfig config = PeakSeacraftMgr.getConfig();
        if (null == config) {
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NOT_IN_PRETIME;
        }
        // 只能在备战期捐献
//        if (!config.isPrepareTime()) {
//            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NOT_IN_PRETIME;
//        }
        if (type != 1 && type != 2) {
            return GameErrorCode.E_BAG_USE_GOODS_COUNT_LESS_ONE;
        }
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        if (PeakSeacraftMgr.canInAndOutUnion(ownUnionId)) {
            return GameErrorCode.E_BAG_USE_GOODS_COUNT_LESS_ONE;//
        }

        if (config.isShipMaxLevel(userData.getDonationExp() + 1)) {
            return GameErrorCode.E_PEAK_SEACRAFT_SHIP_MAX_LEVEL;
        }

        roundReset();
        Property consume = new Property();
        Property reward = new Property();
        int silverDonateNum = 0;
        int expAdd = 0;
        if (type == 1) {
            silverDonateNum = userData.getSilverDonateNum();
            for (int i = 0; i < num; i++) {
                PeakSeacraftDonateConfig donateConfig = null;
                for (PeakSeacraftDonateConfig configTemp : config.getSilverDonateList()) {
                    if (silverDonateNum < configTemp.getId()) {
                        donateConfig = configTemp;
                        break;
                    }
                    donateConfig = configTemp;
                }
                if (null == donateConfig) {
                    return GameErrorCode.E_BAG_USE_GOODS_COUNT_LESS_ONE;
                }
                consume.addProperty(PropertyHelper.parseStringToProperty(donateConfig.getCost()));
                expAdd += donateConfig.getAddPro();
                silverDonateNum++;
            }

        } else {
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(config.getSEACRAFT_CRAFT_DONATE_ITEMS());
            if (null == goodsInfo) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            consume = new Property(goodsInfo.getGoodsId(), num);
            expAdd = goodsInfo.getParamList().get(0).intValue() * num;
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(consume)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            String extendParam = goodsInfo.getExtendParam();
            for (int i = 0; i < num; i++) {
                Property property = RandomWeightConfigHelper.getRandomProperty(extendParam);
                reward.addProperty(property);
            }
        }

        int newExp = userData.getDonationExp() + expAdd;

        if (!player.getModule(CurrencyModule.class).currencyIsEnough(consume)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityDonationShipCost);
        if (!reward.isNothing()) {
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityDonationShipReward);
        }

        userData.setDonationExp(newExp);
        if (type == 1) {
            userData.setSilverDonateNum(silverDonateNum);
        }

        PeakSeacraftProto.PeakSeacraftDonationShipGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftDonationShipGameToCrossMsg.newBuilder();
        gameToCrossMsg.setActivityId(config.getActivityInfo().getActivityId());
        gameToCrossMsg.setUnionId(ownUnionId);
        gameToCrossMsg.setDonateExp(userData.getDonationExp());
        gameToCrossMsg.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        gameToCrossMsg.setType(type);
        gameToCrossMsg.setCost(PropertyHelper.parsePropertyToString(consume));
        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_DONATION_SHIP, gameToCrossMsg, gameToCrossMsg.getActivityId());

        PeakSeacraftProto.PeakSeacraftDonationShipRespMsg.Builder resp = PeakSeacraftProto.PeakSeacraftDonationShipRespMsg.newBuilder();
        resp.setRet(0);
        resp.setReward(PropertyHelper.parsePropertyToString(reward));
        resp.setSilverDonateNum(userData.getSilverDonateNum());
        player.sendPacket(ClientProtocol.U_PEAK_SEACRAFT_DONATION_SHIP, resp);

        synUserData();
        return 0;
    }

    /**
     * 刷新玩家信息 楼层
     */
    private void refreshUserFloor(boolean refresh) {
        PeakSeacraftActivityConfig activityConfig = PeakSeacraftMgr.getConfig();
        if (userData.getFloor() <= 0 || userData.getFloor() > activityConfig.getFloorMap().size()) {
            if (userData.getFloor() > activityConfig.getFloorMap().size()) {
                userData.setGotBigReward(1);
            }
            userData.setFloor(1);
            refresh = true;
        }
        if (refresh || userData.getCellInfoList().isEmpty()) {
            int speclId = PeakSeacraftMgr.randomHelper.next(PeakSeacraftActivityConfig.getPubGribNum());
            userData.getCellInfoList().clear();
            for (int i = 0; i < PeakSeacraftActivityConfig.getPubGribNum(); i++) {
                userData.addCellInfoList(new PeakSeacraftCellInfo(i, i == speclId));
            }
        }
    }

    /**
     * 请求功勋酒馆数据
     *
     * @return
     */
    public PeakSeacraftProto.PeakSeacraftPubRespMsg.Builder getPub() {
        PeakSeacraftProto.PeakSeacraftPubRespMsg.Builder builder = PeakSeacraftProto.PeakSeacraftPubRespMsg.newBuilder();
        if (userData == null) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_GRIB);
            return builder;
        }
        refreshUserFloor(false);
        for (PeakSeacraftCellInfo item : userData.getCellInfoList()) {
            PeakSeacraftProto.PeakSeacraftCellData.Builder cellBuilder = PeakSeacraftProto.PeakSeacraftCellData.newBuilder();
            if (item.isOpen()) {
                cellBuilder.setReward(item.getReward());
            }
            cellBuilder.setOpen(item.isOpen());
            builder.addCell(cellBuilder);
        }
        builder.setGotBigReward(userData.getGotBigReward());
        builder.setFloor(userData.getFloor());
        builder.setRet(0);
        return builder;
    }

    /**
     * 功勋酒馆挖宝
     *
     * @param index
     */
    public PeakSeacraftProto.PeakSeacraftOpenPubRespMsg.Builder openPub(int floor, int index) {
        PeakSeacraftProto.PeakSeacraftOpenPubRespMsg.Builder builder = PeakSeacraftProto.PeakSeacraftOpenPubRespMsg.newBuilder();
        if (userData == null) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_GRIB);
            return builder;
        }
        PeakSeacraftActivityConfig activityConfig = PeakSeacraftMgr.getConfig();
        if (null == activityConfig) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_ID_ERROR);
            return builder;
        }
        refreshUserFloor(false);
        if (userData.getFloor() != floor) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_FLOOR_ERROR);
            return builder;
        }
        if (index < 0 || index + 1 > userData.getCellInfoList().size()) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_ID_ERROR);
            return builder;
        }

        PeakSeacraftCellInfo cellInfo = userData.getCellInfoList().get(index);
        if (cellInfo == null) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_ID_ERROR);
            return builder;
        }
        if (cellInfo.isOpen()) {
            builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_GRID_IS_OPEN);
            return builder;
        }

        SeacraftSouthSeaFloorConfig floorConfig = PeakSeacraftMgr.getConfig().getFloorMap().get(floor);
        if (floorConfig == null) {
            return builder.setRet(GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_FLOOR_ERROR);
        }

        Property cost = PropertyHelper.parseStringToProperty(floorConfig.getConsume());
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(cost)) {
            return builder.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
        }

        Property reward = new Property();
        boolean refresh = false;
        if (cellInfo.isSpecl()) {
            reward.addProperty(PropertyHelper.parseStringToProperty(floorConfig.getSpecialRewardStr()));
            if (floorConfig.getSpecialRewardList().size() > 0) {
                Property randomReward = RandomWeightConfigHelper.getPropertyWeightItem(floorConfig.getSpecialRewardList());
                reward.addProperty(randomReward);
            }
            refresh = true;
        } else {
            Property randomReward = RandomWeightConfigHelper.getPropertyWeightItem(floorConfig.getWeightList());
            reward.addProperty(randomReward);
        }
        cellInfo.setOpen(true);

        player.getModule(CurrencyModule.class).removeCurrency(cost, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityOpenPubCost);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityOpenPubReward);

        String rewardStr = PropertyHelper.parsePropertyToString(reward);
        cellInfo.setReward(rewardStr);
        userData.setUpdateOption();
        if (refresh) {
            userData.setFloor(userData.getFloor() + 1);
            refreshUserFloor(true);
        }
        builder.setFloor(userData.getFloor());
        builder.setReward(rewardStr);
        builder.setSpecial(refresh);
        builder.setRet(0);
        return builder;
    }

    /**
     * 膜拜
     */
    public PeakSeacraftProto.PeakSeacraftWorshipRespMsg.Builder worship() {
        PeakSeacraftProto.PeakSeacraftWorshipRespMsg.Builder builder = PeakSeacraftProto.PeakSeacraftWorshipRespMsg.newBuilder();
        builder.setRet(0);
        if (userData.getWorship() != 0){
            return builder.setRet(GameErrorCode.E_ERROR_DATA);
        }
        userData.setWorship(1);
        Property reward = PropertyHelper.parseStringToProperty(PeakSeacraftMgr.getConfig().getWORSHIP_REWARD());
        player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.PeakSeacraftActivity,eLogMoneyType.PeakSeacraftActivityWroshipReward);
        builder.setReward(PeakSeacraftMgr.getConfig().getWORSHIP_REWARD());

        return builder;
    }

    /**
     * 指定道具转换为邮件
     */
    public void GoodsToMail(int goodsId, long count, eLogMoneyType master, eLogMoneyType son) {
        //回收船桨和火药
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (null == goodsInfo) {
            return;
        }
        String language = player.getLanguage();
        Property reward = new Property();
        Map<String, Long> recycleNameNumMap = new HashMap<>();
        if (count > 0) {
            recycleNameNumMap.put(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), language), count);
            if (goodsId == PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_DONATE_ITEMS()) {
                String extendParam = goodsInfo.getExtendParam();
                for (int i = 0; i < count; i++) {
                    Property property = RandomWeightConfigHelper.getRandomProperty(extendParam);
                    reward.addProperty(property);
                }
            } else {
                for (int i = 0; i < count; i++) {
                    OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(goodsId);
                    if (null != openGoodsBagResult) {
                        reward.addProperty(openGoodsBagResult.getReward());
                    }
                }
            }
        }

        if (!reward.isNothing() && !recycleNameNumMap.isEmpty()) {
            StringBuilder returnStr = new StringBuilder();
            for (Map.Entry<String, Long> entry : recycleNameNumMap.entrySet()) {
                String key = entry.getKey();
                Long value = entry.getValue();
                returnStr.append(ServerLanguageMgr.getContent(key, language)).append("X").append(value).append(", ");
            }
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.PEAKSEACRAFT_REMOVE_ITEM_TITLE, language);
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.PEAKSEACRAFT_REMOVE_ITEM_CONTENT,
                    language), returnStr.toString());
            MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(reward), mailContent, mailTitle);
        }

        PeakSeacraftMgr.getLogger().info("活动{}玩家{}领奖期获得道具{}x{},回收成邮件奖励{},途径{},{}",
                PeakSeacraftMgr.getConfig().getActivityInfo().getActivityId(), player.getUserId(), goodsId, count, PropertyHelper.parsePropertyToString(reward), master, son);
    }

    public int action(PeakSeacraftProto.PeakSeacraftActionReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }
        // 判断是否在活动期
        if (!PeakSeacraftMgr.isOpenTime()) {
            ret = GameErrorCode.E_PEAK_SEACRAFT_ACTIVITY_NO_FIGHT_TIME;
            return ret;
        }
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        if (!PeakSeacraftMgr.isPromotion(ownUnionId)) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_TARGET_NO_PROMOTION;
            return ret;
        }
        roundReset();

        // 操作类型 0 进攻 1突袭 2使用道具进攻 3修复 4 增加小队进攻次数 5 使用船桨
        PeakSeacraftProto.PeakSeacraftActionGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftActionGameToCrossMsg.newBuilder();
        gameToCrossMsg.setActivityId(reqMsg.getActivityId());
        gameToCrossMsg.setCtsMsg(reqMsg);
        gameToCrossMsg.setUnionId(ownUnionId);
        gameToCrossMsg.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        if (reqMsg.getType() == 0) {
            // 攻击
            long count = player.getModule(BagModule.class).getUserBagItemCount(PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_ATTACK_ITEM_ID());
            if (count <= 0) {
                ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                return ret;
            }
            Property property = new Property(PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_ATTACK_ITEM_ID(), count);
            // 预扣除
            player.getModule(PreReduceModule.class).preReduce(property);
            gameToCrossMsg.setPreReduceCount(count);
            gameToCrossMsg.setPropId(PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_ATTACK_ITEM_ID());
        } else if (reqMsg.getType() == 2 || reqMsg.getType() == 3 || reqMsg.getType() == 5) {
            gameToCrossMsg.setTitleId(player.getUserInfo().getTitleId());
            if (reqMsg.getCount() <= 0) {
                ret = GameErrorCode.E_BAG_USE_GOODS_COUNT_LESS_ONE;
                return ret;
            }
            int propId = 0;
            if (reqMsg.getType() == 2) {
                propId = PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_FIRE_ITEM_ID();
            } else if (reqMsg.getType() == 3) {
                propId = PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_WRENCH_ITEM_ID();
            } else if (reqMsg.getType() == 5) {
                if (!PeakSeacraftMgr.getConfig().hasPaddleId(reqMsg.getPropId())) {
                    ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_PADDLE_ID_ERROR;
                    return ret;
                }
                propId = reqMsg.getPropId();
            }
            Property property = new Property(propId, reqMsg.getCount());
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(property)) {
                ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                return ret;
            }
            // 预扣除
            player.getModule(PreReduceModule.class).preReduce(property);
            gameToCrossMsg.setPreReduceCount(reqMsg.getCount());
            gameToCrossMsg.setPropId(propId);
        }
        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_ACTION, gameToCrossMsg, gameToCrossMsg.getActivityId());
        return 0;
    }

    public PeakSeacraftProto.PeakSeacraftActionRespMsg.Builder actionBack(PeakSeacraftProto.PeakSeacraftActionCrossToGameMsg crossToGameMsg) {
        PeakSeacraftProto.PeakSeacraftActionRespMsg.Builder stcMsg = crossToGameMsg.getStcMsg().toBuilder();
        // 取消预扣除道具
        if (crossToGameMsg.getType() == 0 || crossToGameMsg.getType() == 2 || crossToGameMsg.getType() == 3 || crossToGameMsg.getType() == 5) {
            // 取消 预扣除
            Property property = new Property(crossToGameMsg.getPropId(), crossToGameMsg.getCount());
            player.getModule(PreReduceModule.class).restorePreReduce(property);
        }
        if (stcMsg.getRet() == 0) {
            if (crossToGameMsg.getType() == 0 || crossToGameMsg.getType() == 1) {
                //珍兽绑定 鱼类绑定
                for (int patronsId : crossToGameMsg.getPatronsIdList()) {
                    player.getModule(VehicleModule.class).bindPatrons(patronsId, PeakSeacraftMgr.getActivityInfo().getActivityId());
                }
                if (crossToGameMsg.getType() == 0) {
                    Property consume = new Property(crossToGameMsg.getPropId(), stcMsg.getRealConsumeNum());
                    player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityAddAttackCost);
                }
            } else if (crossToGameMsg.getType() == 2) {
                // 道具攻击
                Property consume = new Property(crossToGameMsg.getPropId(), crossToGameMsg.getCount());
                player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropAttackCost);
                // 加宝箱奖励
                OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(crossToGameMsg.getPropId());
                player.getModule(CurrencyModule.class).addCurrency(openGoodsBagResult.getReward(), eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropAttackReward);
                stcMsg.setReward(PropertyHelper.parsePropertyToString(openGoodsBagResult.getReward()));
            } else if (crossToGameMsg.getType() == 3) {
                // 道具修复
                Property consume = new Property(crossToGameMsg.getPropId(), stcMsg.getRealConsumeNum());
                player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropFixCost);
                // 加宝箱奖励
                Property reward = new Property();
                for (int i = 0; i < stcMsg.getRealConsumeNum(); i++) {
                    OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(crossToGameMsg.getPropId());
                    reward.addProperty(openGoodsBagResult.getReward());
                }
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropFixReward);
                stcMsg.setReward(PropertyHelper.parsePropertyToString(reward));
            } else if (crossToGameMsg.getType() == 5) {
                // 使用船桨
                Property consume = new Property(crossToGameMsg.getPropId(), stcMsg.getRealConsumeNum());
                player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropSpeedCost);
                // 加宝箱奖励
                Property reward = new Property();
                for (int i = 0; i < stcMsg.getRealConsumeNum(); i++) {
                    OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(crossToGameMsg.getPropId());
                    reward.addProperty(openGoodsBagResult.getReward());
                }
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityPropSpeedReward);
                stcMsg.setReward(PropertyHelper.parsePropertyToString(reward));

            }
            synUserScore(stcMsg.getAllScore());
        }

        return stcMsg;
    }

    public int buyBuff(PeakSeacraftProto.PeakSeacraftBuyBuffReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }
        // 判断是否在活动期
        if (!PeakSeacraftMgr.getConfig().isOpenTime()) {
            ret = GameErrorCode.E_PEAK_SEACRAFT_ACTIVITY_NO_FIGHT_TIME;
            return ret;
        }
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        if (!PeakSeacraftMgr.isPromotion(ownUnionId)) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_TARGET_NO_PROMOTION;
            return ret;
        }
        int preReduceCount = 0;
        long goldNum = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.Ingots);
        if (goldNum > 0) {
            preReduceCount = (int) Math.min(goldNum, PeakSeacraftMgr.getConfig().maxCostNum);
            Property property = new Property(GameConfig.GAME_MONEY_INGOTS, preReduceCount);
            player.getModule(PreReduceModule.class).preReduce(property);
        }
        PeakSeacraftProto.PeakSeacraftBuyBuffGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftBuyBuffGameToCrossMsg.newBuilder();
        gameToCrossMsg.setActivityId(reqMsg.getActivityId());
        gameToCrossMsg.setCtsMsg(reqMsg);
        gameToCrossMsg.setPreReduceCount(preReduceCount);
        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_BUY_BUFF, gameToCrossMsg, gameToCrossMsg.getActivityId());

        return 0;
    }

    public int challenge(PeakSeacraftProto.PeakSeacraftChallengeReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }
        // 判断是否在活动期
        if (!PeakSeacraftMgr.getConfig().isOpenTime()) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_OPEN;
            return ret;
        }
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        if (!PeakSeacraftMgr.isPromotion(ownUnionId)) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_TARGET_NO_PROMOTION;
            return ret;
        }
        roundReset();
        long goldNum = 0;
        if (reqMsg.getType() == 2) {
            // 一键挑战
            int vipLv = VipMgr.getVipLv(player.getModule(PlayerModule.class).getUserInfo().getVipExp());
            if (vipLv < PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_QUICKFIGHT_LIMIT_VIP()) {
                ret = GameErrorCode.E_VIP_LEVEL_NO_ENOUGH;
                return ret;
            }
            long time = PeakSeacraftMgr.getActivityInfo().getEndTime() - PeakSeacraftMgr.getConfig().getSEACRAFT_CRAFT_QUICKFIGHT_LIMIT_TIME_FINISH() * DateHelper.MINUTE_SECONDS;
            if (DateHelper.getCurrentSecond() > time) {
                ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_END_CLOSE_NOT_ONE_KEY_FIGHT;
                return ret;
            }

            goldNum = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.Ingots);
            // 预扣除
            if (goldNum > 0) {
                player.getModule(PreReduceModule.class).preReduce(new Property(GameConfig.GAME_MONEY_INGOTS, goldNum));
            }
        }
        PeakSeacraftProto.PeakSeacraftChallengeGameToCrossMsg.Builder gameToCross = PeakSeacraftProto.PeakSeacraftChallengeGameToCrossMsg.newBuilder();
        gameToCross.setActivityId(reqMsg.getActivityId());
        gameToCross.setCtsMsg(reqMsg);
        gameToCross.setGoldNum(goldNum);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_CHALLENGE, gameToCross, gameToCross.getActivityId());

        return 0;
    }

    public void challengeBack(PeakSeacraftProto.PeakSeacraftChallengeCrossToGameMsg crossToGameMsg) {
        if (crossToGameMsg.getType() == 2) {
            // 需求预扣除
            if (crossToGameMsg.getGoldNum() > 0) {
                Property property = new Property(GameConfig.GAME_MONEY_INGOTS, crossToGameMsg.getGoldNum());
                player.getModule(PreReduceModule.class).restorePreReduce(property);
            }
        }
        PeakSeacraftProto.PeakSeacraftChallengeRespMsg stcMsg = crossToGameMsg.getStcMsg();
        if (stcMsg.getRet() == 0) {
            // 扣元宝
            if (crossToGameMsg.getType() == 2 && stcMsg.getConsumeGoldNum() > 0) {
                // 扣道具
                Property consume = new Property(GameConfig.GAME_MONEY_INGOTS, stcMsg.getConsumeGoldNum());
                player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityOneKeyChallengeCost);
            }
            // 加道具
            Property winStreakReward = new Property();
            for (PeakSeacraftProto.PeakSeacraftBattleDetail item : stcMsg.getBattleDetailListList()) {
                // 连胜奖励
                winStreakReward.addProperty(PropertyHelper.parseStringToProperty(item.getWinStreakReward()));
            }
            // 连胜奖励
            if (winStreakReward.getGoods().size() > 0) {
                player.getModule(CurrencyModule.class).addCurrency(winStreakReward, eLogMoneyType.PeakSeacraftActivity, eLogMoneyType.PeakSeacraftActivityWinStreakReward);
            }
            // 对决奖励
            battleEnd(stcMsg.getResult());
            // 同步积分
            synUserScore(stcMsg.getAllScore());
        }
        player.sendPacket(ClientProtocol.U_PEAK_SEACRAFT_CHALLENGE, stcMsg.toBuilder());
    }

    public int donationShip(PeakSeacraftProto.PeakSeacraftDonationShipReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }
        if (reqMsg.getNum() > 1000 || reqMsg.getNum() <= 0) {
            ret = GameErrorCode.E_ERROR_DATA;
            return ret;
        }
        return donate(reqMsg.getType(), reqMsg.getNum());
    }

    public int enter(PeakSeacraftProto.PeakSeacraftEnterReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }
        PeakSeacraftActivityConfig config = PeakSeacraftMgr.getConfig();
        if (null == config) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_OPEN;
            return ret;
        }
        // 判断是否在活动期
        if (config.getCurRound() <= 0) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_OPEN;
            return ret;
        }
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        PeakSeacraftProto.PeakSeacraftEnterReqMsgGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftEnterReqMsgGameToCrossMsg.newBuilder();
        gameToCrossMsg.setActivityId(reqMsg.getActivityId());
        gameToCrossMsg.setCtsMsg(reqMsg);
        gameToCrossMsg.setUnionId(ownUnionId);
        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_ENTER, gameToCrossMsg, gameToCrossMsg.getActivityId());

        return 0;
    }

    public int guess(PeakSeacraftProto.PeakSeacraftGuessReqMsg reqMsg) {
        int ret = PeakSeacraftMgr.canEntryActivity(player, reqMsg.getActivityId());
        if (ret != 0) {
            return ret;
        }

        Set<String> set = new HashSet<>(reqMsg.getUnionListList());
        if (reqMsg.getUnionListList().size() == 0 || set.size() != reqMsg.getUnionListList().size()) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_GUESS_UNION_NUM_ERROR;
            return ret;
        }

        // 判断联盟数量
        int num = PeakSeacraftMgr.getConfig().getGuessUnionNum();
        if (num == 0) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_HAVE_GUESS_REWARD;
            return ret;
        }
        if (reqMsg.getUnionListList().size() > num) {
            ret = GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_GUESS_UNION_NUM_ERROR;
            return ret;
        }
        PeakSeacraftProto.PeakSeacraftGuessGameToCrossMsg.Builder gameToCrossMsg = PeakSeacraftProto.PeakSeacraftGuessGameToCrossMsg.newBuilder();
        gameToCrossMsg.setActivityId(reqMsg.getActivityId());
        gameToCrossMsg.setStcMsg(reqMsg);
        String ownUnionId = GameUnionActivityGroupMgr.getUnionUid(PeakSeacraftMgr.getActivityInfo().getActivityId(), player.getUserId());
        gameToCrossMsg.setUnionId(ownUnionId);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_PEAK_SEACRAFT_GUESS, gameToCrossMsg, gameToCrossMsg.getActivityId());

        return 0;
    }
}
